const app = getApp()

Page({
  data: {
    banners: [
      { id: 1, image: '/assets/images/banner1.jpg' },
      { id: 2, image: '/assets/images/banner2.jpg' },
      { id: 3, image: '/assets/images/banner3.jpg' }
    ],
    categories: [
      { id: 1, name: '金属', icon: '/assets/images/metal.png' },
      { id: 2, name: '塑料', icon: '/assets/images/plastic.png' },
      { id: 3, name: '纸类', icon: '/assets/images/paper.png' },
      { id: 4, name: '电器', icon: '/assets/images/electronics.png' },
      { id: 5, name: '玻璃', icon: '/assets/images/glass.png' },
      { id: 6, name: '织物', icon: '/assets/images/textile.png' },
      { id: 7, name: '其他', icon: '/assets/images/other.png' }
    ],
    wasteTypes: [],
    selectedCategory: null,
    searchQuery: ''
  },

  onLoad() {
    this.loadWasteTypes()
  },

  onPullDownRefresh() {
    this.loadWasteTypes()
  },

  loadWasteTypes() {
    const { selectedCategory, searchQuery } = this.data
    let url = `${app.globalData.baseUrl}/pricing/waste-types/`
    
    // 添加查询参数
    const params = []
    if (selectedCategory) {
      params.push(`category=${selectedCategory}`)
    }
    if (searchQuery) {
      params.push(`search=${searchQuery}`)
    }
    if (params.length > 0) {
      url += '?' + params.join('&')
    }

    wx.request({
      url,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            wasteTypes: res.data.results || res.data
          })
        }
      },
      complete: () => {
        wx.stopPullDownRefresh()
      }
    })
  },

  selectCategory(e) {
    const categoryId = e.currentTarget.dataset.id
    this.setData({
      selectedCategory: this.data.selectedCategory === categoryId ? null : categoryId
    }, () => {
      this.loadWasteTypes()
    })
  },

  onSearch(e) {
    const searchQuery = e.detail.value
    this.setData({ searchQuery }, () => {
      // 使用节流函数延迟搜索
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout)
      }
      this.searchTimeout = setTimeout(() => {
        this.loadWasteTypes()
      }, 500)
    })
  },

  goToDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/waste-detail/waste-detail?id=${id}`
    })
  },

  createOrder() {
    // 检查是否登录
    const token = wx.getStorageSync('access_token')
    if (!token) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }

    // 检查用户地区
    wx.showModal({
      title: '温馨提示',
      content: '目前仅支持凉山州布拖县地区的回收服务，其他地区暂未开通，敬请期待！',
      confirmText: '继续下单',
      cancelText: '我知道了',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/create-order/create-order'
          })
        }
      }
    })
  }
}) 